/*	kd:
	
	This implements shopkeeper switching / cycling. A significant change from
	before is that you don't access the gzd menu to change shopkeepers, cuz this
	wouldn't catch shopkeepers added in addons. This makes everything easier
	for us.
	
	*/


struct Gc_Shop_KeeperControl {
	private int						index;
	private bool					is_switching;
	private int						shopkeeper_count;
	
	private Gc_DefaultCvar			cvar_shopkeeper;
	
	void OnInit (Gc_ShopkeeperList shopkeepers) {
		cvar_shopkeeper.Find("gc_shopkeeper");
		index				= cvar_shopkeeper.GetInt(def_val: 0);
		is_switching		= false;
		shopkeeper_count	= shopkeepers ? shopkeepers.Count() : 0;
		
		if(index < 0 || shopkeeper_count <= index) {
			index = 0;
		}
	}
	
	play void OnClose () {
		let max_index = max(0, shopkeeper_count - 1);
		cvar_shopkeeper.SetInt(clamp(index, 0, max_index));
	}
	
	// kd: This cycles to the next shopkeeper. To switch to the next one, you
	// should call remove to get rid of whatever shopkeeper is currently there,
	// and then call spawn to switch to whichever you cycled to.
	
	// This ensures there's always exactly one shopkeeper. (If none is shown,
	// there's still a shopkeeper! It's just an invisible one that stores some
	// info for which item descriptions to use.)
	bool RequestNext () {
		let pending_index = index + 1;
		
		if(shopkeeper_count <= pending_index) {
			pending_index = 0;
		}
		
		if(pending_index != index) {
			index = pending_index;
			return true;
		}
		
		return false;
	}
	
	void Remove () {
		if(!is_switching) {
			Gc_Shop_ToWorld.SendNetworkEvent("RemoveShopkeeper");
			is_switching = true;
		}
	}
	
	void Spawn () {
		Gc_Shop_ToWorld.SendNetworkEvent("SpawnShopkeeper", index);
		is_switching = false;
	}
	
	// this doesn't need "nextstate" because the previous shopkeeper will tell
	// us to call Spawn.
}


